/**
 * Created by Chris on 14-5-25.
 */



$js_btn_upload_img.bind('click',function(){
    upload_file({
        url : "uploadImg",
        field : "file",
        dataType:"json",
        file : document.getElementById('js_logo_file').files[0],
        success:function(response){
            console.log('response='+response);
            response = JSON.parse(response);

            console.log("success!responseText="+response.url);
            $("#js_upload_progress").html("上传成功!<img src='"+response.thumb+"'>");

            $("#js_file_url").val(response.url);
            $("#js_selected_pic").removeAttr('disabled').attr('checked', 'checked');
            // update the logo
            /*
             var $js_user_logo = $("#js_user_logo");
             */
        },
        error:function(e){
            console.error("catch error");
        },
        progress : function(e){
            if(event.lengthComputable) {
                var howmuch =parseInt( (event.loaded / event.total) * 100 );
                console.log("howmuch="+howmuch);
                if (howmuch>=80){
                    howmuch = 80;
                }else{

                }
                $("#js_upload_progress").html("上传进度:"+ howmuch+"%");
            } else {
                console.log("Can't determine the size of the file.");
            }
        }
    });
});



$js_match_live_status.bind('change', function () {
    if (current_live_status!= $js_match_live_status.val()){
        $("#js_btn_update_live_status").removeAttr('disabled');
    }else{
        $("#js_btn_update_live_status").attr('disabled','');
    }

});

$("#js_btn_update_live_status").bind('click', function () {
    $js_match_live_status.attr('disabled', '');
    var live_status =$js_match_live_status.val();

    // ajax post
    $.ajax({
        url : "changeLiveStatus?match_id="+match_id+"&live_status="+live_status,
        method:'post',
        dataType:"json",
        success:function(data){
//                alert("success data="+data);
            console.log("change status success! data.server_time["+data.server_time+"] data.live_update["+data.live_update+"] data.live_status["+data.live_status+"]");
            onLiveStatusChanged(data.live_status, data.live_update, data.server_time);

        },
        error:function(){
            console.log("change status failure");
        },
        complete:function(){
            console.log("change status complete");
        }
    })


//        when success
    $(this).attr('disabled', '');
    $js_match_live_status.removeAttr('disabled', '');
});

function onLiveStatusChanged(liveStatus, liveUpdate, serverTime) {
    console.log("onLiveStatusChanged liveStatus["+liveStatus+"] liveUpdate["+liveUpdate+"] serverTime["+serverTime+"]");
    servertime = serverTime;
    livetime =  liveUpdate;
    current_live_status= liveStatus;

    if (liveStatus=='FIRST_HALF'
        ||liveStatus=='SECOND_HALF'
        ||liveStatus=='EXTRA_TIME'){
        setMatchTimer(true);
    }else{
        setMatchTimer(false);
    }
    if (liveStatus=='FIRST_HALF'){
        livetime_delta_min = 0;
    }
    if (liveStatus=='SECOND_HALF'){
        livetime_delta_min = 45;
    }
    if (liveStatus=='EXTRA_TIME'){
        livetime_delta_min = 90;
    }
    if (liveStatus=='END'){
//        livetime_delta_min = 90;
        $("#js_match_close_live_panel").show();

    }

}

function updateMatchTime(){

//        console.log("updateMatchTime livetime["+livetime+"] servertime["+servertime+"] timediff["+timediff+"]");
    //        var interval = new Date(livetime*1000).getTime() - new Date(servertime*1000).getTime() ;
    var interval =  (new Date().getTime() - new Date(livetime*1000).getTime()) /1000   - timediff ;
//        console.log("updateMatchTime interval="+interval);
//        console.log("livetime_delta_min="+livetime_delta_min);
    $js_match_min.val( parseInt(interval /60) + livetime_delta_min ) ;
    $js_match_sec.val( parseInt(interval %60) ) ;
}

var r_matchTimer = 0;
function setMatchTimer(on){
    if (on){
        if (r_matchTimer){
            clearInterval(r_matchTimer);
        }
        r_matchTimer = setInterval(updateMatchTime, 1000);
    }else{
        clearInterval(r_matchTimer);
    }
}


function reloadList(){
    var url = "messageList?match_id="+match_id+"&aftertime="+aftertime;
    if (loadingList){
        return;
    }
    loadingList = true;
    $.ajax({
        url : url,
        dataType:'json',
        success:function(data){
//                alert("success!");
            loadingList = false;;
//            console.log(data);
            var msgs = data.msgs;
            for (var i=0;i<msgs.length;i++){
                var msg = msgs[i];
                console.log("msg="+msg +" msg.content_meta="+msg.content_meta);

                processLiveMessage(msg, false);
            }

        },
        error:function(data){
            alert("errorerror!");
            loadingList = false;
        }
    });
}
reloadList();
setInterval(reloadList, 3000);

function createMessage(){
    var msg  = $js_txt_content.val();
    if ($.trim(msg)==''){
        alert("请输入内容");
        return;
    }
    if ($("#js_btn_update_live_status").attr('disabled')!='disabled'){
        alert("请调整比赛状态后再发送消息");
        return;
    }

    $js_txt_content.attr('disabled','');
    $js_btn_post.attr('disabled','');
    var guest_point = $js_txt_guest_point.val();
    var host_point = $js_txt_host_point.val();
    var match_min = $js_match_min.val();
    var match_status = $js_match_live_status.val();
    console.log('host_point['+host_point+'] guest_point['+guest_point+'] match_status['+match_status+'] match_min['+match_min +'] msg='+msg);
//        if ()
    var img_url = "";
    if ($("#js_selected_pic:checked").length>0){
        img_url = $("#js_file_url").val();
    }


    var data = "content="+ encodeURIComponent(msg) + "&guest_point="+guest_point
        +"&host_point="+host_point+"&match_id="+match_id
        +"&match_min="+match_min
        +"&img_url="+img_url
        +"&live_status="+match_status;

    $.ajax({
        url: 'createMessage',
        data: data,
        method:'post',
        success:function(){
            $js_txt_content.val('');
            $js_txt_content.focus();
            reloadList();
        },
        error:function(){

            alert("发送消息失败！");
        },
        complete:function(){
            $js_txt_content.removeAttr('disabled');
            $js_btn_post.removeAttr('disabled');

            if ($("#js_selected_pic:checked").length>0){
                clearPic();
            }

        }
    }) ;
}


function clearPic(){
    $("#js_logo_file").val("");
    $("#js_file_url").val("");
    $("#js_selected_pic")
        .removeAttr('checked')
        .attr('disabled', "");

    $("#js_upload_progress").html('');
}

$js_btn_delete_img.bind('click', function(){
    clearPic();
});

$js_btn_post.bind('click',function(){
    createMessage();
});


$("#js_btn_reset_time").bind('click',function(){
    var deltaMin = prompt('请设置比赛当前分钟数', 0);
    if (parseInt(deltaMin)>=0){
        self.location = "updateMatchMin?match_id="+match_id+"&min="+deltaMin;
    }else{
        alert("格式错误！");
    }
});

function processLiveMessage(msg, append){
    if (msg.createtime>aftertime){
        aftertime = msg.createtime;
    }
    if (before_time==-1){
        before_time = msg.createtime;
    } else if ( msg.createtime<before_time){
        before_time = msg.createtime;
    }

    var date = new Date();

    date.setTime(msg.createtime*1000);

    var img = "";
    if (msg.content_meta && msg.content_meta.indexOf("img:")>=0){
        img = "<img src='"+msg.content_meta.substring(4)+".thumb'>";
    }
//    var fmt_date = date.getDate()+" "+date.getHours()+":"+date.getMinutes();
    var fmt_date = msg.createtime;

    var msg_live_status = msg.live_status;
    if (msg_live_status=='READY'){
        msg_live_status = "即将开始";
    }else if (msg_live_status=='HALF_TIME'){
        msg_live_status = "半场休息";
    }else if (msg_live_status=='EXTRA_REST'){
        msg_live_status = "加时休息";
    }else if (msg_live_status=='END'){
        msg_live_status = "比赛结束";
    }else{
        msg_live_status  = msg.match_min+"'";
    }
    var html = "<div>" +
        " <span class='sender'>"+ msg.fullname +": </span>" +
//                        "<span  class='sender'> "+ msg.createtime +"</span>" +
//                        "<span  class='sender'> "+ msg.createtime +"</span>" +
        " <span class='content'>"+ img+ msg.content +"</span>" +
        " <span class='point'>"+ msg.host_point +":" +msg.guest_point+"</span>" +
        " <span class='match_min'>"+ msg_live_status +" (#"+msg.id +")</span>" +
        "</div>";
    if (append){
        $js_message_list.append(html);
    }else{
        $js_message_list.prepend(html);
    }

}

$("#js_btn_load_history").bind('click', function(){
    var url = "messageList?match_id="+match_id+"&before_time="+before_time;
    if (loadingList){
        return;
    }
    loadingList = true;
    $.ajax({
        url : url,
        dataType:'json',
        success:function(data){
//                alert("success!");
            loadingList = false;;
//            console.log(data);
            var msgs = data.msgs;
            for (var i=0;i<msgs.length;i++){
                var msg = msgs[i];
//                console.log("msg="+msg +" msg.content_meta="+msg.content_meta);
                processLiveMessage(msg, true);
                console.log("msg.content="+msg.content);
            }
        },
        error:function(data){
            alert("errorerror!");
            loadingList = false;
        }
    });
});